import sdk from '../core/index';
import { ClientManage } from '../core/index';
import { ClientAction } from "../shared/api_bot/IMassage";
import { analysisIntent, baseScene } from "../core/tool/baseScene";
import { mathType } from "../core/tool/face";
import { wordMap } from "../core/rpg/wordMap";
import { PositionService } from '../service/PositionService';
import { ComType } from '../core/tool/component';
import task_component from '../component/task_component';
import { TaskService } from '../service/TaskService';
import { TaskStatus } from '../core/rpg/types/task';
import { MailService } from '../service/MailService';
import bag_component from '../component/bag_component';
import { RankingService } from '../service/RankingService';
import { RankingType, quality, qualityName, ItemType, 道具枚举 } from '../shared/face/enums';
import { RankingItem } from '../shared/face';
import gameCfg from '../gameCfg';
import DungeonManager from '../core/manage/DungeonManager';
import pop_component from '../component/pop_component';
import { equipService } from '../service/EquipService';
import { rpgService } from '../service/RPGService';
import rpg_component from '../component/rpg_component';
import equip_component from '../component/equip_component';
import { Bag } from '../core/bag';
import WorldBossManager from '../core/manage/WorldBossManager';

export class scene extends baseScene {
    constructor() {
        super();
        this.map.name = '主神空间';
        this.map.enemyCfg = 'default';
        this.map.isCreateEnemy = false;

        // 注册任务指令
        this.registerMapIntent(mathType.完全匹配, '任务', true, this.taskbar, this);

        // 注册测试指令
        this.registerMapIntent(mathType.完全匹配, '测试副本', true, this.testDungeon, this);

        // 注册世界BOSS指令
        this.registerMapIntent(mathType.完全匹配, '攻击BOSS', true, this.attackWorldBoss, this);
    }

    onPosition(data: analysisIntent) {
        const result = PositionService.getPositionInfo(this.map, data.player);
        if (!result.success) {
            data.player.client_text(result.message);
            return;
        }
        let buttomList = [
            { text: '交易所', action: 'tips_webUrl', mathType: mathType.完全匹配, isHideMath: true },
            { text: '锻造', action: 'forgeMain', mathType: mathType.完全匹配, isHideMath: true },
            { text: '任务', action: 'taskbar', mathType: mathType.完全匹配, isHideMath: true },
            { text: '排行榜', action: 'ranking', mathType: mathType.完全匹配, isHideMath: true },
            { text: '邮件', action: 'mail', mathType: mathType.完全匹配, isHideMath: true },
            { text: '仓库', action: 'dev', mathType: mathType.完全匹配, isHideMath: true },
        ]
        let card = result.card!;

        // 获取当前副本信息
        const dungeonInfo = DungeonManager.getDungeonInfo();

        // 获取当前世界BOSS信息
        const bossInfo = WorldBossManager.getWorldBossInfo();

        if (dungeonInfo.status === 'open') {
            card.title('⚔️挑战');
            card.l('🌍新的世界线入口已经开启。进入世界发送[前往]');
            card.l(`🔥难度: ${dungeonInfo.difficulty}`);
            card.l(`🏞️世界线: ${dungeonInfo.name}`);
            const minutes = Math.floor(dungeonInfo.remainingTime / (60 * 1000));
            const seconds = Math.floor((dungeonInfo.remainingTime % (60 * 1000)) / 1000);
            card.l(`⏳关闭倒计时: ${minutes}分${seconds}秒`);
            buttomList.push({ text: '前往', action: 'toGame', mathType: mathType.完全匹配, isHideMath: true });
        } else if (dungeonInfo.status === 'cooldown') {
            const minutes = Math.floor(dungeonInfo.cooldownTime / (60 * 1000));
            const seconds = Math.floor((dungeonInfo.cooldownTime % (60 * 1000)) / 1000);
            card.l(`🌍新的世界线将在${minutes}分${seconds}秒后开启`);
        }

        // 显示世界BOSS状态
        if (bossInfo) {
            // 从BOSS实体获取信息
            const baseCom = bossInfo.bossEntity.getComponent(ComType.base) as any;
            const rpgCom = bossInfo.bossEntity.getComponent(ComType.rpg) as rpg_component;
            
            const bossName = baseCom?.nickName || '未知BOSS';
            const bossEmoji = baseCom?.emoji || '🌍';
            const currentHP = rpgCom?.hp_now || 0;
            const maxHP = (rpgCom as any)?.hp_max || currentHP;
            const hpPercent = maxHP > 0 ? Math.round((currentHP / maxHP) * 100) : 0;
            
            card.title('⚔️世界BOSS');
            card.l(`🌍世界BOSS-${bossEmoji}${bossName} 已经出现`);
            card.l(`🌍HP ${currentHP}/${maxHP} (${hpPercent}%)`);
            card.l(`🌍参与发送[攻击BOSS]`);
            
            if (bossInfo.status === 'spawned') {
                const countdown = WorldBossManager.getNextBattleCountdown();
                card.l(`⏳下次战斗倒计时${countdown}秒`);
            } else if (bossInfo.status === 'fighting') {
                card.l('⚔️战斗中...');
            } else if (bossInfo.status === 'dead') {
                card.l('💀已被击败！');
            } else if (bossInfo.status === 'cooldown') {
                const cooldownRemaining = Math.ceil((bossInfo.cooldownEndTime - Date.now()) / 1000);
                card.l(`⏳生成冷却中，${cooldownRemaining}秒后出现新BOSS`);
            }
        } else {
            card.title('⚔️世界BOSS');
            card.l('🌍当前没有世界BOSS');
        }
        this.registerButtonIntents(card, buttomList);
        data.player.client_text(card.getText());
    }

    /**
     * 锻造所主页
     */
    forgeMain(data: analysisIntent) {
        const card = sdk.tool.card.create();
        card.title('🔨锻造所');
        card.l('请选择要使用的功能');
        card.l('[强化]强化后装备可以获得更高的属性');
        card.l('[进化]可以提升装备的品质');
        card.l('[附魔]可使装备附带额外的技能');
        card.l('[技能升级]可以升级装备的技能');
        card.l('[分解]分解装备可以获得材料');
        this.registerButtonIntents(card, [
            { text: '强化', action: 'forgeStrengthenSelect', mathType: mathType.完全匹配, isHideMath: true },
            { text: '进化', action: 'evolveSelect', mathType: mathType.完全匹配, isHideMath: true },
            { text: '附魔', action: 'enchantSelect', mathType: mathType.完全匹配, isHideMath: true },
            { text: '技能升级', action: 'skillUpgradeSelect', mathType: mathType.完全匹配, isHideMath: true },
            { text: '分解', action: 'disassembleSelect', mathType: mathType.完全匹配, isHideMath: true },
        ]);
        data.player.client_text(card.getText());
    }
    /**
     * 选择强化
     * @param data 
     * @returns 
     */
    forgeStrengthenSelect(data: analysisIntent) {
        let _player = data.player;
        let com_pop = data.player.getComponent(ComType.对话框) as pop_component;
        const card = sdk.tool.card.create();
        card.title('🔨强化机');
        card.l('请直接输入[ID]来选择背包中要强化的装备');
        card.title('装备列表');
        const bagCom = data.player.getComponent(ComType.背包) as bag_component;
        if (!bagCom) {
            _player.client_text('背包组件未找到');
            return;
        }
        let equipList = bagCom.getEquipList();
        equipList.forEach((item, index) => {
            card.l(`[${index + 1}]${item.name}+${item.data.strengthenLevel}`);
        });

        com_pop.setContent(card.getText());
        com_pop.lisen((_data: analysisIntent) => {
            let index_data = sdk.tool.common.cover_number(_data.Message.content);
            // 选择强化的index
            let index = index_data.k1;
            if (!index) {
                _player.client_text('请输入[强化 + ID]来选择背包中要强化的装备');
                return;
            }
            // 选择背包中的装备
            let com_bag = _player.getComponent(ComType.背包) as bag_component;
            if (!com_bag) {
                _player.client_text('背包组件未找到');
                return;
            }
            let equipList = com_bag.getEquipList();
            let equip = equipList[index - 1];
            if (!equip) {
                _player.client_text('背包中没有该装备');
                return;
            }
            const card = sdk.tool.card.create();
            card.title('🔨强化机');
            card.l(`选择装备:${equip.name}`);
            card.l(`强化等级:${equip.data.strengthenLevel}`);
            card.title('强化预览');
            const rates = equipService.getStrengthenRates(equip.data.strengthenLevel);
            const toPercent = (v: number) => `${Math.round(v * 100)}%`;
            card.l(`成功:${toPercent(rates.success)}`);
            card.l(`不变:${toPercent(rates.none)}`);
            card.l(`失败(降级):${toPercent(rates.fail)}`);
            const confirmButtonConfigs = [
                {
                    text: '确认',
                    mathType: mathType.完全匹配,
                    action: () => {
                        const result = equipService.tryStrengthen(equip.data);
                        const msgCard = sdk.tool.card.create();
                        msgCard.title('🔨强化结果');
                        msgCard.l(`装备:${equip.name}`);
                        msgCard.l(`原等级:${result.beforeLevel} -> 现等级:${result.afterLevel}`);
                        const mapText: { [key: string]: string } = { success: '成功(+1级)', none: '未变化', fail: '失败(-1级，最低1级)' };
                        msgCard.l(`结果:${mapText[result.result] || '未知结果'}`);
                        _data.player.client_text(msgCard.getText());
                        com_pop.close();
                    }
                },
                {
                    text: '取消',
                    mathType: mathType.完全匹配,
                    action: () => com_pop.close()
                }
            ];
            com_pop.registerPopupButtonIntents(confirmButtonConfigs, this, card);
            _data.player.client_text(card.getText());

        })
        com_pop.active();
    }

    /**
     * 进化：选择装备 -> 显示当前品质与目标品质、成功率 -> 确认进化
     */
    evolveSelect(data: analysisIntent) {
        const player = data.player;
        const com_pop = player.getComponent(ComType.对话框) as pop_component;
        const bagCom = player.getComponent(ComType.背包) as bag_component;
        if (!bagCom) {
            player.client_text('背包组件未找到');
            return;
        }
        const list = bagCom.getEquipList();
        const card = sdk.tool.card.create();
        card.title('🧬进化台');
        card.l('请直接输入[ID]来选择背包中要进化的装备');
        card.title('装备列表');
        list.forEach((item, idx) => {
            const qName = Object.values(qualityName)[item.data.quality] || '未知';
            card.l(`[${idx + 1}]${item.name}·${qName} +${item.data.strengthenLevel}`);
        });
        com_pop.setContent(card.getText());
        com_pop.lisen((_data: analysisIntent) => {
            const idxData = sdk.tool.common.cover_number(_data.Message.content);
            const index = idxData.k1;
            if (!index) {
                player.client_text('请输入[进化 + ID]来选择背包中要进化的装备');
                return;
            }
            const equip = list[index - 1];
            if (!equip) {
                player.client_text('背包中没有该装备');
                return;
            }
            const e = equip.data;
            const card2 = sdk.tool.card.create();
            card2.title('🧬进化台');
            card2.l(`选择装备:${equip.name}`);
            const curQName = Object.values(qualityName)[e.quality];
            if (e.quality >= quality.SSR) {
                card2.l(`当前品质:${curQName}`);
                card2.l('已达最高品质，无法继续进化');
                _data.player.client_text(card2.getText());
                return;
            }
            const targetQ = (e.quality + 1) as quality;
            const targetQName = Object.values(qualityName)[targetQ];
            const rate = equipService.getEvolveSuccessRate(e.quality);
            card2.l(`当前品质:${curQName} -> 目标:${targetQName}`);
            card2.l(`成功率:${Math.round(rate * 100)}%`);
            const confirm = [
                {
                    text: '确认',
                    mathType: mathType.完全匹配,
                    action: () => {
                        const res = equipService.tryEvolve(e);
                        const rc = sdk.tool.card.create();
                        rc.title('🧬进化结果');
                        rc.l(`装备:${equip.name}`);
                        const bq = Object.values(qualityName)[res.beforeQuality];
                        const aq = Object.values(qualityName)[res.afterQuality];
                        rc.l(`品质:${bq} -> ${aq}`);
                        rc.l(`结果:${res.success ? '成功' : (res.canEvolve ? '失败' : '不可进化')}`);
                        _data.player.client_text(rc.getText());
                        com_pop.close();
                    }
                },
                {
                    text: '取消',
                    mathType: mathType.完全匹配,
                    action: () => com_pop.close()
                }
            ];
            com_pop.registerPopupButtonIntents(confirm, this, card2);
            _data.player.client_text(card2.getText());
        });
        com_pop.active();
    }

    /**
     * 分解：选择装备 -> 显示将获得的碎片数量 -> 确认分解
     */
    disassembleSelect(data: analysisIntent) {
        const player = data.player;
        const com_pop = player.getComponent(ComType.对话框) as pop_component;
        const bagCom = player.getComponent(ComType.背包) as bag_component;
        if (!bagCom) {
            player.client_text('背包组件未找到');
            return;
        }
        const list = bagCom.getEquipList();
        if(list.length === 0){
            player.client_text('背包中没有装备');
            return;
        }
        const card = sdk.tool.card.create();
        card.title('🧱分解台');
        card.l('请直接输入[ID]来选择背包中要分解的装备');
        card.title('装备列表');
        list.forEach((item, idx) => {
            const qName = Object.values(qualityName)[item.data.quality] || '未知';
            card.l(`[${idx + 1}]${item.name}·${qName} +${item.data.strengthenLevel}`);
        });
        com_pop.setContent(card.getText());
        com_pop.lisen((_data: analysisIntent) => {
            const idxData = sdk.tool.common.cover_number(_data.Message.content);
            const index = idxData.k1;
            if (!index) {
                player.client_text('请输入[分解 + ID]来选择背包中要分解的装备');
                return;
            }
            const equipItem = list[index - 1];
            if (!equipItem) {
                player.client_text('背包中没有该装备');
                return;
            }
            const level = Math.max(0, Math.floor(equipItem.data.strengthenLevel || 0));
            const shardCount = Math.floor(level * (level + 1) / 2);
            const card2 = sdk.tool.card.create();
            card2.title('🧱分解台');
            card2.l(`分解装备:${equipItem.name}`);
            card2.l(`装备等级:+${equipItem.data.strengthenLevel}`);
            const curQName = Object.values(qualityName)[equipItem.quality];
            card2.l(`装备品质: ${curQName}`);
            const confirm = [
                {
                    text: '确认',
                    mathType: mathType.完全匹配,
                    action: () => {
                        // 从背包移除该装备
                        const removed = bagCom.delItem(equipItem, 1);
                        if (!removed) {
                            _data.player.client_text('分解失败: 移除装备失败');
                            com_pop.close();
                            return;
                        }
                        let disassembleCard = sdk.tool.card.create();
                        disassembleCard.title('🧱分解完成');
                        disassembleCard.l(`已分解:${equipItem.name}`);
                        const disassembleBag = new Bag();
                        // 发放碎片：道具枚举.强化碎片，数量=等差求和 n*(n+1)/2
                        disassembleBag.addItem(sdk.prop.createProp({
                            type: ItemType.道具,
                            id: 道具枚举.强化碎片,
                            count: shardCount
                        }));
                        bagCom.addBag(disassembleBag);
                        disassembleCard.merge(disassembleBag.getCard('🧱分解获得'));
                        _data.player.client_text(disassembleCard.getText());
                        com_pop.close();
                    }
                },
                {
                    text: '取消',
                    mathType: mathType.完全匹配,
                    action: () => com_pop.close()
                }
            ];
            com_pop.registerPopupButtonIntents(confirm, this, card2);
            _data.player.client_text(card2.getText());
        });
        com_pop.active();
    }

    
    toGame(data: analysisIntent) {
        // 检查是否可以进入副本
        if (!DungeonManager.canEnterDungeon()) {
            data.player.client_text('❌ 世界线入口已关闭，请等待下次开启');
            return;
        }

        // 获取当前副本信息
        const dungeonInfo = DungeonManager.getDungeonInfo();
        if (dungeonInfo.status !== 'open') {
            data.player.client_text('❌ 世界线入口已关闭，请等待下次开启');
            return;
        }

        // 切换到副本地图，并设置难度
        this.switchMap(data.player, dungeonInfo.name, dungeonInfo.difficulty);
    }

    /**
     * 附魔：选择装备 -> 显示当前技能、可附魔技能、成功率 -> 确认附魔
     */
    enchantSelect(data: analysisIntent) {
        const player = data.player;
        const com_pop = player.getComponent(ComType.对话框) as pop_component;
        const bagCom = player.getComponent(ComType.背包) as bag_component;
        if (!bagCom) {
            player.client_text('背包组件未找到');
            return;
        }
        const list = bagCom.getEquipList();
        if(list.length === 0){
            player.client_text('背包中没有装备');
            return;
        }
        const card = sdk.tool.card.create();
        card.title('✨附魔台');
        card.l('请直接输入[ID]来选择背包中要附魔的装备');
        card.title('装备列表');
        list.forEach((item, idx) => {
            const skillCount = item.data.skill ? item.data.skill.length : 0;
            card.l(`[${idx + 1}]${item.name} +${item.data.strengthenLevel} (技能:${skillCount}个)`);
        });
        com_pop.setContent(card.getText());
        com_pop.lisen((_data: analysisIntent) => {
            const idxData = sdk.tool.common.cover_number(_data.Message.content);
            const index = idxData.k1;
            if (!index) {
                player.client_text('请输入[附魔 + ID]来选择背包中要附魔的装备');
                return;
            }
            const equip = list[index - 1];
            if (!equip) {
                player.client_text('背包中没有该装备');
                return;
            }
            const e = equip.data;
            const card2 = sdk.tool.card.create();
            card2.title('✨附魔台');
            card2.l(`选择装备:${equip.name}`);
            card2.l(`当前技能数量:${e.skill ? e.skill.length : 0}`);
            
            // 显示当前技能
            if (e.skill && e.skill.length > 0) {
                card2.l('当前技能:');
                e.skill.forEach((skill: any, idx: number) => {
                    card2.l(`  ${idx + 1}. ${skill.reName || skill.skillId}`);
                });
            }
            
            // 获取可附魔的技能
            const availableSkills = equipService.getEnchantableSkills(e);
            if (availableSkills.length === 0) {
                card2.l('没有可附魔的技能');
                _data.player.client_text(card2.getText());
                com_pop.close();
                return;
            }
            
            card2.l(`可附魔技能数量:${availableSkills.length}`);
            const successRate = equipService.getEnchantSuccessRate(e);
            card2.l(`成功率:${Math.round(successRate * 100)}%`);
            
            const confirm = [
                {
                    text: '确认',
                    mathType: mathType.完全匹配,
                    action: () => {
                        const res = equipService.tryEnchant(e);
                        const rc = sdk.tool.card.create();
                        rc.title('✨附魔结果');
                        rc.l(`装备:${equip.name}`);
                        rc.l(`结果:${res.success ? '成功' : '失败'}`);
                        rc.l(`消息:${res.message}`);
                        if (res.success && res.addedSkill) {
                            rc.l(`新增技能:${res.addedSkill.reName || res.addedSkill.skillId}`);
                            rc.l(`技能数量:${res.beforeSkillCount} -> ${res.afterSkillCount}`);
                        }
                        _data.player.client_text(rc.getText());
                        com_pop.close();
                    }
                },
                {
                    text: '取消',
                    mathType: mathType.完全匹配,
                    action: () => com_pop.close()
                }
            ];
            com_pop.registerPopupButtonIntents(confirm, this, card2);
            _data.player.client_text(card2.getText());
        });
        com_pop.active();
    }

    /**
     * 技能升级：选择装备 -> 选择技能 -> 确认升级
     */
    skillUpgradeSelect(data: analysisIntent) {
        const player = data.player;
        const com_pop = player.getComponent(ComType.对话框) as pop_component;
        const bagCom = player.getComponent(ComType.背包) as bag_component;
        if (!bagCom) {
            player.client_text('背包组件未找到');
            return;
        }
        const list = bagCom.getEquipList();
        if(list.length === 0){
            player.client_text('背包中没有装备');
            return;
        }
        const card = sdk.tool.card.create();
        card.title('🔧技能升级台');
        card.l('请直接输入[ID]来选择背包中要升级技能的装备');
        card.title('装备列表');
        list.forEach((item, idx) => {
            const skillCount = item.data.skill ? item.data.skill.length : 0;
            const upgradeableCount = equipService.getUpgradeableSkills(item.data).length;
            card.l(`[${idx + 1}]${item.name} +${item.data.strengthenLevel} (技能:${skillCount}个, 可升级:${upgradeableCount}个)`);
        });
        com_pop.setContent(card.getText());
        com_pop.lisen((_data: analysisIntent) => {
            const idxData = sdk.tool.common.cover_number(_data.Message.content);
            const index = idxData.k1;
            if (!index) {
                player.client_text('请输入装备编号来选择要升级技能的装备');
                return;
            }
            const equip = list[index - 1];
            if (!equip) {
                player.client_text('背包中没有该装备');
                return;
            }
            const e = equip.data;
            
            // 检查装备是否有技能
            if (!e.skill || e.skill.length === 0) {
                player.client_text('该装备没有技能，无法升级');
                com_pop.close();
                return;
            }

            // 获取可升级的技能
            const upgradeableSkills = rpgService.getUpgradeableSkills(e);
            if (upgradeableSkills.length === 0) {
                player.client_text('该装备的所有技能都已达到最大等级');
                com_pop.close();
                return;
            }

            // 显示技能选择界面
            this.showSkillUpgradeSelection(player, com_pop, equip, upgradeableSkills);
        });
        com_pop.active();
    }

    /**
     * 显示技能升级选择界面
     */
    private showSkillUpgradeSelection(player: any, com_pop: pop_component, equip: any, upgradeableSkills: any[]) {
        const card = sdk.tool.card.create();
        card.title('🔧技能升级台');
        card.l(`选择装备: ${equip.name}`);
        card.l(`可升级技能数量: ${upgradeableSkills.length}`);
        card.title('可升级技能列表');
        
        upgradeableSkills.forEach((skill, idx) => {
            const currentLevel = skill.level || 1;
            const maxLevel = skill.maxLevel || 10;
            const successRate = rpgService.getSkillUpgradeSuccessRate(equip.data, skill.skillId);
            card.l(`[${idx + 1}] ${skill.reName || skill.skillId} (${currentLevel}/${maxLevel}) 成功率:${Math.round(successRate * 100)}%`);
        });

        com_pop.setContent(card.getText());
        com_pop.lisen((_data: analysisIntent) => {
            const idxData = sdk.tool.common.cover_number(_data.Message.content);
            const skillIndex = idxData.k1;
            
            if (!skillIndex) {
                player.client_text('请输入技能编号来选择要升级的技能');
                return;
            }
            
            const selectedSkill = upgradeableSkills[skillIndex - 1];
            if (!selectedSkill) {
                player.client_text('无效的技能编号');
                return;
            }

            // 显示升级确认界面
            this.showUpgradeConfirmation(player, com_pop, equip, selectedSkill);
        });
        
        // 注册取消按钮
        const cancelButtonConfigs = [
            {
                text: '取消',
                mathType: mathType.完全匹配,
                action: () => com_pop.close()
            }
        ];
        com_pop.registerPopupButtonIntents(cancelButtonConfigs, this, card);
        com_pop.active();
    }

    /**
     * 显示升级确认界面
     */
    private showUpgradeConfirmation(player: any, com_pop: pop_component, equip: any, skill: any) {
        // 关闭之前的对话框
        com_pop.close();
        
        // 创建新的确认对话框
        const confirmPop = player.getComponent(ComType.对话框) as pop_component;
        const card = sdk.tool.card.create();
        card.title('🔧技能升级确认');
        card.l(`装备: ${equip.name}`);
        card.l(`技能: ${skill.reName || skill.skillId}`);
        card.l(`当前等级: ${skill.level || 1}`);
        card.l(`升级后等级: ${(skill.level || 1) + 1}`);
        card.l(`最大等级: ${skill.maxLevel || 10}`);
        card.l(`成功率: 100%`);

        const confirmButtonConfigs = [
            {
                text: '确认',
                mathType: mathType.完全匹配,
                action: () => {
                    const result = rpgService.upgradeSkill(equip.data.skill, skill.skillId);

                    const resultCard = sdk.tool.card.create();
                    resultCard.title('🔧技能升级结果');
                    resultCard.l(`装备: ${equip.name}`);
                    resultCard.l(`技能: ${skill.reName || skill.skillId}`);
                    resultCard.l(`结果: ${result.success ? '成功' : '失败'}`);
                    resultCard.l(`消息: ${result.message}`);
                    if (result.success) {
                        resultCard.l(`等级变化: ${result.beforeLevel} -> ${result.afterLevel}`);
                        equip.data.skill = result.newSkills;
                    }
                    player.client_text(resultCard.getText());
                    confirmPop.close();
                }
            },
            {
                text: '取消',
                mathType: mathType.完全匹配,
                action: () => confirmPop.close()
            }
        ];
        confirmPop.registerPopupButtonIntents(confirmButtonConfigs, this, card);
        confirmPop.setContent(card.getText());
        confirmPop.active();
    }

    dev(data: analysisIntent) {
        data.player.client_text('测试中功能');
    }

    // 测试副本系统
    testDungeon(data: analysisIntent) {
        DungeonManager.testDungeonSystem();
        const dungeonInfo = DungeonManager.getDungeonInfo();
        data.player.client_text(`世界线测试信息:\n${JSON.stringify(dungeonInfo, null, 2)}`);
    }

    // 攻击世界BOSS
    attackWorldBoss(data: analysisIntent) {
        const player = data.player;
        
        // 检查是否可以攻击BOSS
        if (!WorldBossManager.canAttackBoss()) {
            player.client_text('❌ 当前没有可攻击的世界BOSS');
            return;
        }

        // 玩家报名攻击BOSS
        const registered = WorldBossManager.registerForBattle(player.id);
        if (!registered) {
            player.client_text('❌ 报名失败，可能已经报名或BOSS状态异常');
            return;
        }

        // 获取BOSS信息
        const bossInfo = WorldBossManager.getWorldBossInfo();
        if (!bossInfo) {
            player.client_text('❌ 获取BOSS信息失败');
            return;
        }

        // 从BOSS实体获取信息
        const baseCom = bossInfo.bossEntity.getComponent(ComType.base) as any;
        const rpgCom = bossInfo.bossEntity.getComponent(ComType.rpg) as rpg_component;
        
        const bossName = baseCom?.nickName || '未知BOSS';
        const bossEmoji = baseCom?.emoji || '🌍';
        const currentHP = rpgCom?.hp_now || 0;
        const maxHP = (rpgCom as any)?.hp_max || currentHP;
        
        // 显示报名成功信息
        const card = sdk.tool.card.create();
        card.title('⚔️ 世界BOSS攻击报名成功');
        card.l(`🌍 BOSS: ${bossEmoji}${bossName}`);
        card.l(`💀 HP: ${currentHP}/${maxHP}`);
        card.l(`⚔️ 当前参与者: ${bossInfo.participants.length}人`);
        
        const countdown = WorldBossManager.getNextBattleCountdown();
        card.l(`⏰ 下次战斗: ${countdown}秒后`);
        card.l('');
        card.l('🎯 你已成功报名，战斗开始时会自动参与！');
        card.l('💡 提示：每5秒进行一次战斗，所有参与者共享战斗结果');

        player.client_text(card.getText());
    }

    // 邮件指令处理
    async mail(data: analysisIntent) {
        console.log(`玩家查看邮件，ID: ${data.player.id}`);
        const mailResult = await MailService.getUserMails(data.player.id);
        await this.showMailList(data.player, mailResult);
    }

    // 查看邮件指令处理
    async view_mail(data: analysisIntent) {
        const mailResult = await MailService.getUserMails(data.player.id);
        await this.viewSpecificMail(data.player, mailResult.mails, data);
    }

    // 查看全部邮件指令处理
    async view_all_mail(data: analysisIntent) {
        const mailResult = await MailService.getUserMails(data.player.id);
        await this.viewAllMails(data.player, mailResult.mails);
    }

    // 发送邮件指令处理
    send_mail(data: analysisIntent) {
        data.player.client_text('请前往http://dew-bot.cn/test/client/mail/send');
    }

    // 排行榜指令处理
    async ranking(data: analysisIntent) {
        // 动态注册排行榜二级指令
        this.registerRankingSubCommands(data.player);

        let card = sdk.tool.card.create();
        card.title('🏆排行榜单');
        card.l('请选择要查看的排行榜类型：');
        card.l('');
        card.l('📊等级排行⚔️战力排行');
        card.l('💰金币排行📅签到排行');
        card.l('💡提示：排行榜每7天结算一次，前100名可获得奖励！');

        this.registerRankingMenuButtons(card);
        data.player.client_text(card.getText());
    }

    // 重写taskbar方法，显示全部任务
    async taskbar(data: analysisIntent) {
        const tasks = await TaskService.getPlayerTasks(data.player);

        // 动态注册二级任务指令
        this.registerTaskSubCommands(data.player);

        this.showTaskList(data.player, tasks);
    }

    /**
     * 动态注册任务二级指令
     * @param player 玩家对象
     */
    private registerTaskSubCommands(player: any) {
        // 注册二级指令到当前场景
        const subCommands = [
            { command: '每日任务', action: this.daily_task.bind(this) },
            { command: '每周任务', action: this.weekly_task.bind(this) },
            { command: '每月任务', action: this.monthly_task.bind(this) },
            { command: '限时任务', action: this.limited_task.bind(this) },
            { command: '全服任务', action: this.server_task.bind(this) },
            { command: '世界任务', action: this.world_task.bind(this) }
        ];

        subCommands.forEach(({ command, action }) => {
            this.registerMapIntent(
                mathType.完全匹配,
                command,
                true,
                action,
                this
            );
        });

        console.log('📋 已注册任务二级指令到场景:', subCommands.map(cmd => cmd.command));
    }

    /**
     * 动态注册排行榜二级指令
     * @param player 玩家对象
     */
    private registerRankingSubCommands(player: any) {
        // 注册二级指令到当前场景
        const subCommands = [
            { command: '等级排行榜', action: this.showLevelRanking.bind(this) },
            { command: '金币排行榜', action: this.showGoldRanking.bind(this) },
            { command: '签到排行榜', action: this.showSignRanking.bind(this) },
            { command: '战力排行榜', action: this.showPowerRanking.bind(this) }
        ];

        subCommands.forEach(({ command, action }) => {
            this.registerMapIntent(
                mathType.完全匹配,
                command,
                false, // 不隐藏，让用户可以看到这些指令
                action,
                this
            );
        });

        console.log('📋 已注册排行榜二级指令到场景:', subCommands.map(cmd => cmd.command));
    }

    /**
     * 注册排行榜菜单按钮
     * @param card 卡片对象
     */
    private registerRankingMenuButtons(card: any) {
        const buttonConfigs = [
            { text: '等级排行', action: 'showLevelRanking', mathType: mathType.完全匹配, isHideMath: true },
            { text: '金币排行', action: 'showGoldRanking', mathType: mathType.完全匹配, isHideMath: true },
            { text: '签到排行', action: 'showSignRanking', mathType: mathType.完全匹配, isHideMath: true },
            { text: '战力排行', action: 'showPowerRanking', mathType: mathType.完全匹配, isHideMath: true }
        ];

        this.registerButtonIntents(card, buttonConfigs);
    }

    // 排行榜显示方法
    async showLevelRanking(data: analysisIntent) {
        await this.showRanking(RankingType.等级, '等级排行榜', '📊', data);
    }

    async showGoldRanking(data: analysisIntent) {
        await this.showRanking(RankingType.金币, '金币排行榜', '💰', data);
    }

    async showSignRanking(data: analysisIntent) {
        await this.showRanking(RankingType.签到, '签到排行榜', '📅', data);
    }

    async showPowerRanking(data: analysisIntent) {
        await this.showRanking(RankingType.战力, '战力排行榜', '⚔️', data);
    }

    /**
     * 显示排行榜
     * @param type 排行榜类型
     * @param title 标题
     * @param emoji 图标
     * @param data 分析意图数据
     */
    private async showRanking(type: RankingType, title: string, emoji: string, data: analysisIntent) {
        try {
            let resultData = {
                title: `${emoji}${title}`,
                rankRankName: type,
                ranks: [] as RankingItem[],
                myRank: {
                    rank: 0,
                    score: 0,
                    playerName: '',
                    playerEmoji: '',
                },
            }
            // 获取排行榜数据
            let rankingData = RankingService.getRankingData(type, 100); // 显示前50名

            // 如果数据为空，尝试初始化数据
            if (rankingData.length === 0) {
                await RankingService.initializeRankingData();
                rankingData = RankingService.getRankingData(type, 100);
            }

            // 显示排行榜
            for (let i = 0; i < 10; i++) {
                if (rankingData[i]) {
                    resultData.ranks.push(rankingData[i]);
                } else {
                    resultData.ranks.push({
                        rank: i + 1,
                        score: 0,
                        playerName: '匿名玩家',
                        playerEmoji: '🧙',
                        playerId: '0',
                        lastUpdateTime: 0,
                    });
                }
            }
            // 显示玩家自己的排名
            const playerRank = RankingService.getPlayerRank(data.player.id, type);

            // 从排行榜数据中查找玩家信息
            const playerRankingData = rankingData.find((item: RankingItem) => item.playerId === data.player.id);

            // 获取玩家详细信息
            const baseCom = data.player.getComponent(ComType.base) as any;

            if (playerRank > 0 && playerRankingData) {
                resultData.myRank = {
                    rank: playerRank,
                    score: playerRankingData.score,
                    playerName: '我的排名',
                    playerEmoji: playerRankingData.playerEmoji,
                };
            } else {
                resultData.myRank = {
                    rank: 999,
                    score: 0,
                    playerName: '我的排名',
                    playerEmoji: baseCom ? baseCom.emoji : '🧙',
                };
            }

            data.player.client_img('ranking', resultData);
        } catch (error) {
            console.error('显示排行榜失败:', error);
            data.player.client_text('显示排行榜失败，请稍后重试');
        }
    }



    // 每日任务指令处理
    async daily_task(data: analysisIntent) {
        const tasks = await TaskService.getPlayerTasks(data.player);
        this.showDailyTasks(data.player, tasks.daily);
    }

    // 每周任务指令处理
    async weekly_task(data: analysisIntent) {
        const tasks = await TaskService.getPlayerTasks(data.player);
        this.showWeeklyTasks(data.player, tasks.weekly);
    }

    // 每月任务指令处理
    async monthly_task(data: analysisIntent) {
        const tasks = await TaskService.getPlayerTasks(data.player);
        this.showMonthlyTasks(data.player, tasks.monthly);
    }

    // 限时任务指令处理
    async limited_task(data: analysisIntent) {
        const tasks = await TaskService.getPlayerTasks(data.player);
        this.showLimitedTasks(data.player, tasks.limited);
    }

    // 世界任务指令处理
    async world_task(data: analysisIntent) {
        const com_pos = data.player.getComponent(ComType.位置) as any;
        if (!com_pos || !com_pos.sceneName || com_pos.sceneName === 'default' || com_pos.sceneName === '主神空间') {
            data.player.client_text('🌍 世界任务只在特定地图中可用');
            return;
        }

        const tasks = await TaskService.getPlayerTasks(data.player);
        if (tasks.world && tasks.world.length > 0) {
            this.showWorldTasks(data.player, tasks.world);
        } else {
            data.player.client_text('🌍 当前地图暂无世界任务');
        }
    }

    // 处理世界任务结算
    async handleSettleWorldTasks(data: analysisIntent) {
        const result = await TaskService.settleWorldTasks(data.player);

        if (result.success) {
            let card = sdk.tool.card.create();
            card.title('🎉世界任务结算成功!');
            card.l(result.message);

            if (result.rewards && result.rewards.length > 0) {
                card.l('┄━═🎁获得奖励═━┄');
                result.rewards.forEach((reward: any) => {
                    card.l(`🎁${reward.name} x${reward.count}`);
                });
            }

            data.player.client_text(card.getText());
        } else {
            data.player.client_text(`❌结算失败: ${result.message}`);
        }
    }

    // 全服任务指令处理
    async server_task(data: analysisIntent) {
        const tasks = await TaskService.getPlayerTasks(data.player);
        this.showServerTasks(data.player, tasks.server);
    }

    // 显示任务列表
    private async showTaskList(player: any, tasks: any) {
        let card = sdk.tool.card.create();
        card.title('📋任务栏');

        // 检查全服任务完成状态
        for (const serverTask of tasks.server) {
            await TaskService.checkServerTaskCompletion(player, serverTask.taskId);
        }

        // 计算各类型任务的状态和进度
        const taskStatus = this.calculateTaskStatus(tasks);

        // 世界任务
        if (tasks.world && tasks.world.length > 0) {
            const worldTaskStatus = this.calculateWorldTaskStatus(tasks.world);
            const statusEmoji = worldTaskStatus.completed > 0 ? '✅' : '🔄';
            const progress = Math.floor((worldTaskStatus.progress / worldTaskStatus.target) * 100);
            card.l(`🌍世界任务${statusEmoji}${worldTaskStatus.completed > 0 ? '已完成' : '进行中'}(${progress}%)`);
        }

        // 限时任务
        if (taskStatus.limited.total > 0) {
            const statusEmoji = taskStatus.limited.completed > 0 ? '✅' : '🔄';
            const progress = Math.floor((taskStatus.limited.progress / taskStatus.limited.target) * 100);
            card.l(`⏰限时任务${statusEmoji}${taskStatus.limited.completed > 0 ? '已完成' : '进行中'}(${progress}%)`);
        }

        // 每日任务
        if (taskStatus.daily.total > 0) {
            const statusEmoji = taskStatus.daily.completed > 0 ? '✅' : '🔄';
            const progress = Math.floor((taskStatus.daily.progress / taskStatus.daily.target) * 100);
            card.l(`📅每日任务${statusEmoji}${taskStatus.daily.completed > 0 ? '已完成' : '进行中'}(${progress}%)`);
        }

        // 每周任务
        if (taskStatus.weekly.total > 0) {
            const statusEmoji = taskStatus.weekly.completed > 0 ? '✅' : '🔄';
            const progress = Math.floor((taskStatus.weekly.progress / taskStatus.weekly.target) * 100);
            card.l(`📆每周任务${statusEmoji}${taskStatus.weekly.completed > 0 ? '已完成' : '进行中'}(${progress}%)`);
        }

        // 每月任务
        if (taskStatus.monthly.total > 0) {
            const statusEmoji = taskStatus.monthly.completed > 0 ? '✅' : '🔄';
            const progress = Math.floor((taskStatus.monthly.progress / taskStatus.monthly.target) * 100);
            card.l(`📅每月任务${statusEmoji}${taskStatus.monthly.completed > 0 ? '已完成' : '进行中'}(${progress}%)`);
        }

        // 全服任务
        if (taskStatus.server.total > 0) {
            const statusEmoji = taskStatus.server.completed > 0 ? '✅' : '🔄';
            const progress = Math.floor((taskStatus.server.progress / taskStatus.server.target) * 100);
            card.l(`🌍全服任务${statusEmoji}${taskStatus.server.completed > 0 ? '已完成' : '进行中'}(${progress}%)`);
        }

        // 添加按钮
        const buttons = [
            { text: '每日任务', action: 'daily_task', mathType: mathType.完全匹配, isHideMath: true },
            { text: '每周任务', action: 'weekly_task', mathType: mathType.完全匹配, isHideMath: true },
            { text: '每月任务', action: 'monthly_task', mathType: mathType.完全匹配, isHideMath: true },
            { text: '全服任务', action: 'server_task', mathType: mathType.完全匹配, isHideMath: true },
            { text: '限时任务', action: 'limited_task', mathType: mathType.完全匹配, isHideMath: true },
        ];

        // 如果有世界任务，添加世界任务按钮
        if (tasks.world && tasks.world.length > 0) {
            buttons.push({ text: '世界任务', action: 'world_task', mathType: mathType.完全匹配, isHideMath: true });
        }

        this.registerButtonIntents(card, buttons);

        player.client_text(card.getText());
    }

    // 计算任务状态
    private calculateTaskStatus(tasks: any) {
        const status = {
            daily: { total: 0, completed: 0, progress: 0, target: 0 },
            weekly: { total: 0, completed: 0, progress: 0, target: 0 },
            monthly: { total: 0, completed: 0, progress: 0, target: 0 },
            server: { total: 0, completed: 0, progress: 0, target: 0 },
            limited: { total: 0, completed: 0, progress: 0, target: 0 },
            world: { total: 0, completed: 0, progress: 0, target: 0 }
        };

        // 计算每日任务状态
        tasks.daily.forEach((task: any) => {
            status.daily.total++;
            if (task.status === TaskStatus.已领取) {
                status.daily.completed++;
            }
            // 计算进度和目标
            task.targets.forEach((target: any) => {
                status.daily.progress += Math.min(target.current, target.count);
                status.daily.target += target.count;
            });
        });

        // 计算每周任务状态
        tasks.weekly.forEach((task: any) => {
            status.weekly.total++;
            if (task.status === TaskStatus.已领取) {
                status.weekly.completed++;
            }
            // 计算进度和目标
            task.targets.forEach((target: any) => {
                status.weekly.progress += Math.min(target.current, target.count);
                status.weekly.target += target.count;
            });
        });

        // 计算每月任务状态
        tasks.monthly.forEach((task: any) => {
            status.monthly.total++;
            if (task.status === TaskStatus.已领取) {
                status.monthly.completed++;
            }
            // 计算进度和目标
            task.targets.forEach((target: any) => {
                status.monthly.progress += Math.min(target.current, target.count);
                status.monthly.target += target.count;
            });
        });

        // 计算全服任务状态 - 使用实时共享进度
        for (const task of tasks.server) {
            status.server.total++;
            if (task.status === TaskStatus.已领取) {
                status.server.completed++;
            }
            // 获取实时全服进度
            const serverProgress = TaskService.getServerTaskProgress(task.taskId);
            if (serverProgress) {
                // 使用实时全服进度
                task.targets.forEach((target: any) => {
                    status.server.progress += Math.min(serverProgress.totalProgress, target.count);
                    status.server.target += target.count;
                });
            } else {
                // 如果没有全服进度数据，使用本地数据
                task.targets.forEach((target: any) => {
                    status.server.progress += Math.min(target.current, target.count);
                    status.server.target += target.count;
                });
            }
        }

        // 计算限时任务状态
        tasks.limited.forEach((task: any) => {
            status.limited.total++;
            if (task.status === TaskStatus.已领取) {
                status.limited.completed++;
            }
            // 计算进度和目标
            task.targets.forEach((target: any) => {
                status.limited.progress += Math.min(target.current, target.count);
                status.limited.target += target.count;
            });
        });

        // 计算世界任务状态
        if (tasks.world) {
            tasks.world.forEach((task: any) => {
                status.world.total++;
                if (task.status === TaskStatus.已领取) {
                    status.world.completed++;
                }
                // 计算进度和目标
                task.targets.forEach((target: any) => {
                    status.world.progress += Math.min(target.current, target.count);
                    status.world.target += target.count;
                });
            });
        }

        return status;
    }

    // 计算世界任务状态
    private calculateWorldTaskStatus(worldTasks: any[]) {
        const status = { total: 0, completed: 0, progress: 0, target: 0 };

        worldTasks.forEach((task: any) => {
            status.total++;
            if (task.status === TaskStatus.已领取) {
                status.completed++;
            }
            // 计算进度和目标
            task.targets.forEach((target: any) => {
                status.progress += Math.min(target.current, target.count);
                status.target += target.count;
            });
        });

        return status;
    }

    // 显示每日任务
    private showDailyTasks(player: any, dailyTasks: any[]) {
        let card = sdk.tool.card.create();
        card.title('📅每日任务');

        if (dailyTasks.length === 0) {
            card.l('暂无每日任务');
        } else {
            // 从第一个任务配置中获取描述信息
            const firstTaskConfig = TaskService.getTaskConfigs().find(t => t.type === '每日任务');
            if (firstTaskConfig && firstTaskConfig.description) {
                card.l(firstTaskConfig.description);
            }

            // 显示任务进度
            for (const task of dailyTasks) {
                this.addDetailedTaskToCard(card, task, 'daily');
            }
        }

        player.client_text(card.getText());
    }

    // 添加奖励汇总
    private addRewardSummary(card: any, tasks: any[]) {
        const allRewards: any[] = [];

        tasks.forEach((task: any) => {
            const taskConfig = TaskService.getTaskConfigs().find(t => t.id === task.taskId);
            if (taskConfig && taskConfig.rewards.length > 0) {
                taskConfig.rewards.forEach((reward: any) => {
                    allRewards.push(reward);
                });
            }
        });

        if (allRewards.length > 0) {
            card.title('🎁任务奖励');
            allRewards.forEach((reward: any) => {
                card.l(`🎁${reward.name} x${reward.count}`);
            });
        }
    }

    // 显示每周任务
    private showWeeklyTasks(player: any, weeklyTasks: any[]) {
        let card = sdk.tool.card.create();
        card.title('📆每周任务');

        if (weeklyTasks.length === 0) {
            card.l('暂无每周任务');
        } else {
            // 从第一个任务配置中获取描述信息
            const firstTaskConfig = TaskService.getTaskConfigs().find(t => t.type === '每周任务');
            if (firstTaskConfig && firstTaskConfig.description) {
                card.l(firstTaskConfig.description);
            }

            // 显示任务进度
            for (const task of weeklyTasks) {
                this.addDetailedTaskToCard(card, task, 'weekly');
            }
        }

        player.client_text(card.getText());
    }

    // 显示每月任务
    private showMonthlyTasks(player: any, monthlyTasks: any[]) {
        let card = sdk.tool.card.create();
        card.title('📅每月任务');

        if (monthlyTasks.length === 0) {
            card.l('暂无每月任务');
        } else {
            // 从第一个任务配置中获取描述信息
            const firstTaskConfig = TaskService.getTaskConfigs().find(t => t.type === '每月任务');
            if (firstTaskConfig && firstTaskConfig.description) {
                card.l(firstTaskConfig.description);
            }

            // 显示任务进度
            for (const task of monthlyTasks) {
                this.addDetailedTaskToCard(card, task, 'monthly');
            }
        }

        player.client_text(card.getText());
    }

    // 显示限时任务
    private showLimitedTasks(player: any, limitedTasks: any[]) {
        let card = sdk.tool.card.create();
        card.title('⏰限时任务');

        if (limitedTasks.length === 0) {
            card.l('暂无限时任务');
        } else {
            // 从第一个任务配置中获取描述信息
            const firstTaskConfig = TaskService.getTaskConfigs().find(t => t.type === '限时任务');
            if (firstTaskConfig && firstTaskConfig.description) {
                card.l(firstTaskConfig.description);
            }

            for (const task of limitedTasks) {
                this.addDetailedTaskToCard(card, task, 'limited');
            }
        }

        player.client_text(card.getText());
    }

    // 显示全服任务
    private showServerTasks(player: any, serverTasks: any[]) {
        let card = sdk.tool.card.create();
        card.title('🌍全服任务');

        if (serverTasks.length === 0) {
            card.l('暂无全服任务');
        } else {
            // 从第一个任务配置中获取描述信息
            const firstTaskConfig = TaskService.getTaskConfigs().find(t => t.type === '全服任务');
            if (firstTaskConfig && firstTaskConfig.description) {
                card.l(firstTaskConfig.description);
            }

            // 检查每个全服任务的完成状态
            for (const task of serverTasks) {
                TaskService.checkServerTaskCompletion(player, task.taskId);
                this.addDetailedTaskToCard(card, task, 'server');
            }
        }

        player.client_text(card.getText());
    }



    // 添加详细任务到卡片（用于单独显示任务类型）
    private addDetailedTaskToCard(card: any, task: any, type: string) {
        const taskConfig = TaskService.getTaskConfigs().find(t => t.id === task.taskId);
        if (!taskConfig) return;

        let statusEmoji = '';

        switch (task.status) {
            case TaskStatus.进行中:
                statusEmoji = '🔄';
                break;
            case TaskStatus.已领取:
                statusEmoji = '✅';
                break;
            case TaskStatus.已过期:
                statusEmoji = '⏰';
                break;
            default:
                statusEmoji = '⏳';
        }

        // 显示任务名称作为独立标题
        const taskName = task.name || taskConfig.name || `任务${task.taskId}`;
        card.title(`📋${taskName}${statusEmoji}`);

        // 显示任务进度
        for (const target of task.targets) {
            let progress = Math.min(target.current, target.count);

            // 全服任务使用实时共享进度
            if (type === 'server') {
                const serverProgress = TaskService.getServerTaskProgress(task.taskId);
                if (serverProgress) {
                    progress = Math.min(serverProgress.totalProgress, target.count);
                }
            }

            // 移除描述中的次数信息，只保留动作描述
            const cleanDescription = target.description.replace(/\d+次/g, '').trim();
            card.l(`${statusEmoji}${cleanDescription}(${progress}/${target.count})次`);
        }

        // 显示任务奖励
        if (taskConfig.rewards && taskConfig.rewards.length > 0) {
            card.title('🎁任务奖励');
            taskConfig.rewards.forEach((reward: any) => {
                card.l(`🎁${reward.name} x${reward.count}`);
            });
        }

        // 如果是限时任务，显示剩余时间
        if (type === 'limited' && taskConfig.duration) {
            const now = Date.now();
            const endTime = task.startTime + (taskConfig.duration * 60 * 1000);
            const remaining = Math.max(0, endTime - now);
            const minutes = Math.floor(remaining / (60 * 1000));
            const seconds = Math.floor((remaining % (60 * 1000)) / 1000);
            card.l(`⏰剩余时间: ${minutes}分${seconds}秒`);
        }
    }

    // 显示邮件列表
    private async showMailList(player: any, mailResult: any) {
        let card = sdk.tool.card.create();
        card.title('📧我的邮件');

        if (!mailResult.success) {
            card.l('获取邮件失败');
            player.client_text(card.getText());
            return;
        }

        if (mailResult.mails.length === 0) {
            card.l('你没有未读的邮件哦~');
        } else {
            // 过滤出未读邮件
            const unreadMails = mailResult.mails.filter((mail: any) => !mail.read);

            card.l(`✉️未读邮件: ${unreadMails.length}条`);

            for (let i = 0; i < unreadMails.length; i++) {
                const element = unreadMails[i];
                card.l(`[${i + 1}] ${element.title}`);
            }
        }

        // 添加按钮
        this.registerButtonIntents(card, [
            { text: '查看', action: 'view_mail', mathType: mathType.开头匹配, isHideMath: true },
            { text: '查看全部', action: 'view_all_mail', mathType: mathType.完全匹配, isHideMath: true },
            { text: '发送邮件', action: 'send_mail', mathType: mathType.完全匹配, isHideMath: true },
        ]);

        player.client_text(card.getText());
    }

    // 查看指定邮件
    private async viewSpecificMail(player: any, mails: any[], data: analysisIntent) {
        const index_data = sdk.tool.common.cover_number(data.Message.content);
        let lookIdx = 0;
        if (index_data.k1) {
            lookIdx = index_data.k1 - 1;
        }

        // 获取所有邮件列表（包括已读和未读）
        const info = mails[lookIdx];

        if (!info) {
            player.client_text('邮件不存在');
            return;
        }

        let locaBag = new Bag();
        let hasItems = false;

        if (!info.read && info.items && info.items.length) {
            // 将奖励放入背包
            hasItems = true;
            info.items.forEach((item: any) => {
                locaBag.addItem(item);
            });

            const bag_com = player.getComponent(ComType.背包) as bag_component;
            bag_com.addBag(locaBag);
        }

        info.read = true;

        // 标记邮件为已读并删除个人邮件
        if (info.from_id === 'sys') {
            // 系统邮件记录已读状态
            await sdk.mail.markSystemMailAsRead(player.id, info._id);
        } else {
            // 个人邮件标记为已读并从内存中删除
            await sdk.mail.markAsRead(info._id);
            await sdk.mail.deleteMail(info._id);
        }

        const card = sdk.tool.card.create();
        card.title('📧邮件详情');
        card.l(`🚩${info.title}`);
        card.l(`🪄[来自${info.from_id}]: ${info.msg}`);

        if (hasItems) {
            card.merge(locaBag.getCard('🎁邮件附件'));
        }

        player.client_text(card.getText());
    }

    // 查看全部邮件
    private async viewAllMails(player: any, mails: any[]) {
        const unreadMailsWithItems = mails.filter((v: any) => { return !v.read && v.items.length });

        if (!unreadMailsWithItems.length) {
            player.client_text('没有未读邮件了~');
            return;
        }

        const bag_com = player.getComponent(ComType.背包) as bag_component;
        let totalClaimedItems = 0;
        const claimedItemsDisplay: string[] = [];

        for (const mail of unreadMailsWithItems) {
            // 使用Bag来处理物品
            const locaBag = new Bag();
            mail.items.forEach((item: any) => {
                locaBag.addItem(item);
            });

            // 添加到背包
            bag_com.addBag(locaBag);

            // 记录领取的物品
            totalClaimedItems += mail.items.length;
            mail.items.forEach((item: any) => {
                claimedItemsDisplay.push(`${item.emoji || '📦'} ${item.name} x${item.count}`);
            });

            // 标记为已读
            mail.read = true;

            // 标记邮件为已读
            if (mail.from_id === 'sys') {
                // 系统邮件记录已读状态
                await sdk.mail.markSystemMailAsRead(player.id, mail._id);
            } else {
                // 个人邮件标记为已读
                await sdk.mail.markAsRead(mail._id);
            }
        }

        let card = sdk.tool.card.create();
        card.title('📧邮件查看');
        card.l(`🎁已查看并领取${unreadMailsWithItems.length}条邮件`);

        if (claimedItemsDisplay.length > 0) {
            card.title('🎁全部附件');
            claimedItemsDisplay.forEach(item => card.l(item));
        }

        player.client_text(card.getText());
    }
}
export default new scene();